package com.chao.tlias.filter;

import com.chao.tlias.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 使用过滤器实现token校验
 */
//@WebFilter(urlPatterns = "/*")
@Slf4j
public class tokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //1.获取请求Url
        String requestURI = request.getRequestURI();

        //2.判断请求Url是否包含login，如果包含则放行
        if (requestURI.contains("login")){
            log.info("本次请求是登录操作，放行....");
            filterChain.doFilter(request,response);
            return;
        }

        //3.从请求头中获取令牌（token）
        String token = request.getHeader("token");

        //4.判断令牌是否存在，如果不存在，响应401
        if (token==null||token.isEmpty()){
            log.info("令牌为空，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //5.令牌存在，解析token，如果解析失败，响应401
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("令牌错误，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //6.校验通过，放行
        filterChain.doFilter(request,response);

    }
}
